# -*- coding: utf-8 -*-

from subprocess import Popen, PIPE
from django.db import connection


def execute_sql(sql):
    """
    原生sql 执行方法
    :param sql: sql语句
    :return: list
    """
    mysql = connection.cursor()
    mysql.execute(sql)
    # 结果转换成dict
    rowList = []
    col_names = [desc[0] for desc in mysql.description]
    row = mysql.fetchall()
    for list in row:
        tMap = dict(zip(col_names, list))
        rowList.append(tMap)
    return rowList


def execute_shell(cmd):
    """
    执行shell
    """
    res = Popen(cmd, shell=True, stdout=PIPE)
    outs, errs = res.communicate()
    try:
        msg = outs.strip('\n')
    except Exception:
        msg = None
    return msg


def string_to_list(string):
    """
    字符串转list
    :param string:
    :return:
    """
    if not string:
        return string
    elif not isinstance(string, str):
        return string

    # list形式的string
    if '[' in string and ']' in string:
        _string = string.replace('[', '')
        _string = _string.replace(']', '')
        if '"'in _string:
            _string = _string.replace('"', '')
        elif "'" in _string:
            _string = _string.replace("'", '')
        if _string:
            _list = []
            _strings = _string.split(',')
            for __string in _strings:
                _list.append(__string.strip())
        else:
            _list = []
    elif ',' in string:
        # 以逗号(,)分隔
        _list = []
        _strings = string.split(',')
        for __string in _strings:
            _list.append(__string.strip())
    elif ' ' in string:
        # 以空格(,)分隔
        _list = string.split(' ')
    else:
        _list = [string]
    return _list


def is_true(string):
    """
    判断字符串是否为true/false/none的string形式
    """
    try:
        _string = string.lower()
    except Exception as e:
        return False
    if _string == 'true':
        return True
    elif _string == 'false':
        return False
    elif _string == 'none':
        return False
    return False